﻿using System;
using System.Collections.Generic;
using System.Data;
using CoreSoft.Frame.Entity;
using CoreSoft.Frame.Entity.http;
using U8API.Pub;
using U8Login;
using UFIDA.U8.MomServiceCommon;

namespace U8API.Plugin
{
    public class ArromsourcePlugin
    {
        //private readonly string _ip = ConfigurationManager.AppSettings["WmsIP"] + "Arromsourceapi";
        public static string constr = "";
        private string url = "";

        private String GetCustJs(clsLogin login, MSXML2.IXMLDOMDocument2 domhead,   MSXML2.IXMLDOMDocument2 dombody, int operation)
        {
            var datatable = Common.GetUrl(constr, login.get_cAcc_Id()).Tables[0];
            var datarow = datatable.Rows[0];
            url = datarow[1] + "Arromsourceapi";
            //var qzcode = datarow[2].ToString();
            //DebugWriteLog.WriteLine("cAcc_Id:" + login.get_cAcc_Id() + ",qzcode:" + qzcode);
            var datatabledept = Common.GetUser(constr).Tables[0];
            DebugWriteLog.WriteLine("cAcc_Id:" + login.get_cAcc_Id() + ",count:" + datatabledept.Rows.Count);
            bool hasdept = false;
            foreach (DataRow item in datatabledept.Rows)
            {
                //部门code
                var deptcode = item[1].ToString();
                //过滤如果不是QZ不触发插件
                if (deptcode == login.get_cAcc_Id())
                {
                    DebugWriteLog.WriteLine("cAcc_Id:" + login.get_cAcc_Id() + ",deptcode:" + deptcode);
                    hasdept = true;
                }
            }
            if (!hasdept)//限制
            {
                return "Nopermission";
            }
            
            Int32 StartFlag = 0;
            //MSXML2.IXMLDOMNode tmpNode = domhead.selectSingleNode("/customer");
            //String custcode = tmpNode.attributes.getNamedItem("ccuscode").nodeValue.ObjToString();
            //String custname = tmpNode.attributes.getNamedItem("ccusname").nodeValue.ObjToString();
            //string ccode = tmpNode.attributes.getNamedItem("ccccode").nodeValue.ObjToString();
            MSXML2.IXMLDOMNode tmphead = domhead.selectSingleNode("//z:row");

            string omcode = tmphead.attributes.getNamedItem("ccode").nodeValue.ObjToString();//订单编号
            int omid = tmphead.attributes.getNamedItem("moid").nodeValue.ObjToInt32();//订单id
            int cbustype = tmphead.attributes.getNamedItem("cbustype").nodeValue.ObjToInt32();//业务类型
            string vencode = tmphead.attributes.getNamedItem("cvencode").nodeValue.ObjToString();//供应商编号
            DateTime podate = tmphead.attributes.getNamedItem("ddate").nodeValue.ObjToDate();//单据时间
            string depcode = tmphead.attributes.getNamedItem("cdepcode").nodeValue.ObjToString();//部门编码
            string usercode = tmphead.attributes.getNamedItem("cpersoncode").nodeValue.ObjToString();//人员编码
            string bz = tmphead.attributes.getNamedItem("cexch_name").nodeValue.ObjToString();//币种 cexch_name 
            float exchangeRate = tmphead.attributes.getNamedItem("nflat").nodeValue.ObjToFloat();//汇率
            float taxRate = tmphead.attributes.getNamedItem("itaxrate").nodeValue.ObjToFloat();//税率 iTaxRate
            //string xxx = dombody

            //MSXML2.IXMLDOMNodeList tmpbody = dombody.selectNodes("//z:row");
            string sql = "select ivouchrowno,modetailsid,iquantity,cinvcode," +
                         "iunitprice,itaxprice,imoney,isum,itax,inatunitprice,inatmoney,inatsum,inattax,cFree1,cFree2,cFree3 " +
                         "from OM_MODetails where moid = " + omid + "";
            var table = DbHelperSQL.Query(sql, constr, null).Tables[0];
            List<Arromsourceapi> dlist = new List<Arromsourceapi>();
            foreach (DataRow item in table.Rows)
            {
                //int omseq = item.attributes.getNamedItem("ivouchrowno").nodeValue.ObjToInt32();//行号
                //int omdid = item.attributes.getNamedItem("modetailsid").nodeValue.ObjToInt32();//字表ID
                //decimal qty = item.attributes.getNamedItem("iquantity").nodeValue.ObjToDecimal();//数量
                //string cinvCode = item.attributes.getNamedItem("cinvcode").nodeValue.ObjToString();//存货编码
                
                Arromsourceapi m = new Arromsourceapi();
                m.OmCode = omcode;
                m.OmID = omid;
                m.OmDid = item["modetailsid"].ObjToInt32();
                m.OmSeq = item["ivouchrowno"].ObjToInt32();
                m.CinvCode = item["cinvcode"].ObjToString();
                m.Qty = item["iquantity"].ObjToDecimal();
                m.CBusType = cbustype;
                m.VendorCode = vencode;
                m.DeptCode = depcode;
                m.UserCode = usercode;
                m.PoDate = podate;
                m.Bz = bz;
                m.ExchangeRate = exchangeRate;
                m.TaxRate = taxRate;
                m.OriPrice = item["iunitprice"].ObjToDecimal();
                m.OriTaxPrice = item["itaxprice"].ObjToDecimal();
                m.IOriSum = item["imoney"].ObjToDecimal();//iMoney
                m.IOriTaxSum = item["isum"].ObjToDecimal();
                m.IOriTax = item["itax"].ObjToDecimal();
                m.Status = StartFlag;
                m.LocalPrice = item["inatunitprice"].ObjToDecimal();
                //m.LocalTaxPrice = item.attributes.getNamedItem("inatunitprice").nodeValue.ObjToString();
                m.ILocalSum = item["inatmoney"].ObjToDecimal();
                m.ILocalTaxSum = item["inatmoney"].ObjToDecimal();
                m.IlocalTax = item["inatmoney"].ObjToDecimal();
                m.Free1 = item["cFree1"].ToString();
                m.Free2 = item["cFree2"].ToString();
                m.Free3 = item["cFree3"].ToString();
                dlist.Add(m);
            }

            string sql2 = "select MOMaterialsID,MoDetailsID,MOID,cInvCode,iQuantity,irowno from OM_MOMaterials where moid = " + omid;

            var table2 = DbHelperSQL.Query(sql2, constr, null).Tables[0];
            List<Moandommaterielsapi> mlist = new List<Moandommaterielsapi>();
            foreach (DataRow item in table2.Rows)
            {
                Moandommaterielsapi obj = new Moandommaterielsapi();
                obj.BillCode = item["MOID"].ToString();
                obj.DetailId = item["MoDetailsID"].ToString();
                obj.AllocateId = item["MOMaterialsID"].ToString();
                obj.BillSeq = item["irowno"].ObjToInt32();
                obj.CinvCode = item["cInvCode"].ToString();
                obj.OmFlag = 1;
                obj.SumNeedQty = item["iQuantity"].ObjToInt32();
                obj.Id = Guid.NewGuid().ToString();
                obj.Status = StartFlag;

                mlist.Add(obj);
            }

            Arromandmomateriels end = new Arromandmomateriels();
            end.OmList = dlist;
            end.OmandmoList = mlist;



            ApiRequest req = new ApiRequest();
            req.data = end;
            req.orgcode = login.get_cAcc_Id();
            req.primarykey = omid.ToString();
            req.operation = operation;
            DebugWriteLog.WriteLine(req.ToJson());
            return req.ToJson();
        }
        public bool Update_After(ref MSXML2.IXMLDOMDocument2 domhead, ref  MSXML2.IXMLDOMDocument2 dombody, ref string errMsg)
        {
            //获取插件上下文
            bool bresult = true;
            MomCallContext ctx = MomCallContextCache.Instance.CurrentMomCallContext;

            //从上下文获取U8Login对象
            U8Login.clsLogin login = ctx.U8Login as U8Login.clsLogin;
            if (login != null)
                constr = login.UFDataConnstringForNet;
            String js;
            try
            {
                js = GetCustJs(login, domhead, dombody, 2);

                var result = HttpHelper.PostDataToServer(url, js);
                var apiresult = Common.DeserializeObject<ApiResponse>(result);
                if (apiresult.successful != 0)
                {
                    errMsg = apiresult.message;
                    return false;
                }
                return true;
            }
            catch (Exception ex)
            {
                bresult = false;
                errMsg = ex.Message;
            }
            return bresult;
        }
        public bool Insert_After(ref MSXML2.IXMLDOMDocument2 domhead, ref MSXML2.IXMLDOMDocument2 dombody, ref string errMsg)
        {
            //获取插件上下文
            bool bresult = true;
            MomCallContext ctx = MomCallContextCache.Instance.CurrentMomCallContext;

            //从上下文获取U8Login对象
            U8Login.clsLogin login = ctx.U8Login as U8Login.clsLogin;
            if (login != null)
                constr = login.UFDataConnstringForNet;
            String js;
            try
            {
                js = GetCustJs(login, domhead, dombody, 0);

                var result = HttpHelper.PostDataToServer(url, js);
                var apiresult = Common.DeserializeObject<ApiResponse>(result);
                if (apiresult.successful != 0)
                {
                    errMsg = apiresult.message;
                    return false;
                }
                return true;
            }
            catch (Exception ex)
            {
                bresult = false;
                errMsg = ex.Message;
            }
            return bresult;
        }
        public bool Delete_After(ref MSXML2.IXMLDOMDocument2 domhead, ref  MSXML2.IXMLDOMDocument2 dombody, ref string errMsg)
        {
            //获取插件上下文
            bool bresult = true;
            MomCallContext ctx = MomCallContextCache.Instance.CurrentMomCallContext;

            //从上下文获取U8Login对象
            U8Login.clsLogin login = ctx.U8Login as U8Login.clsLogin;
            if (login != null)
                constr = login.UFDataConnstringForNet;
            String js;
            try
            {
                js = GetCustJs(login, domhead, dombody, 1);

                var result = HttpHelper.PostDataToServer(url, js);
                var apiresult = Common.DeserializeObject<ApiResponse>(result);
                if (apiresult.successful != 0)
                {
                    errMsg = apiresult.message;
                    return false;
                }
                return true;
            }
            catch (Exception ex)
            {
                bresult = false;
                errMsg = ex.Message;
            }
            return bresult;
        }
    }
}